package services

import (
	"colly/pkg/healthcheck"
	"colly/pkg/tool"
	"context"
	"github.com/Dreamacro/clash/adapter"
	"github.com/Dreamacro/clash/constant"
	"net"
	"time"
)

type ClashProxyConn struct {
	NetConn net.Conn
	Proxy   constant.Proxy
}

func RandomConn(proxyFilePath, url string) *ClashProxyConn {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()

	addr, err := healthcheck.UrlToMetadata(url)
	if err != nil {
		panic(err.Error())
	}
	px := tool.RandomProxySimple(proxyFilePath)
	proxy, err := adapter.ParseProxy(px)
	conn, err := proxy.DialContext(ctx, &addr)
	if err != nil {
		return RandomConn(proxyFilePath, url)
	}
	return &ClashProxyConn{NetConn: conn, Proxy: proxy}
}
